package com.daoshu.mds.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daoshu.component.response.ResponseCallBack;
import com.daoshu.component.response.ResponseCriteria;
import com.daoshu.component.response.ResponseInfo;
import com.daoshu.mds.system.service.ILoginLogService;
import com.daoshu.system.entity.CpLoginLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author zhangmingxin
 */
@RestController
@AllArgsConstructor
@RequestMapping(value = "/loginLog")
@Api(value = "登录日志",tags = "登录日志")
public class LoginLogController {
    private final ILoginLogService logService;

    @GetMapping(value = "/list")
    @ApiOperation(value = "列表展示登录日志")
    public ResponseInfo list(@RequestParam(value = "searchTerm",required = false)@ApiParam(value = "搜索条件",name = "searchTerm") String searchTerm,
                             @RequestParam(value = "page",required = false)@ApiParam(value = "页数",name = "page",defaultValue = "1") Integer page,
                             @RequestParam(value = "size",required = false)@ApiParam(value = "分页大小",name = "size",defaultValue = "10") Integer size){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria responseCriteria, Object... objects) {
                QueryWrapper<CpLoginLog> queryWrapper = new QueryWrapper<>();
                if(!StringUtils.isEmpty(searchTerm)){
                    queryWrapper.like("number",searchTerm)
                            .or()
                            .like("name",searchTerm)
                            .or()
                            .like("ip",searchTerm)
                            .or()
                            .like("org",searchTerm);
                }
                queryWrapper.orderByDesc("create_time");
                IPage<CpLoginLog> logs = logService.page(new Page<>(page,size),queryWrapper);
                logs.getRecords().parallelStream().filter(r->r.getCreateTime()!=null).forEach(r->r.setLoginDateTime(r.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
                responseCriteria.addSingleResult(logs);
            }
        }.sendRequest();
    }
}
